package cn.jtfadmin.base.doc.swagger;

import com.fasterxml.jackson.databind.introspect.AnnotatedField;
import com.fasterxml.jackson.databind.introspect.BeanPropertyDefinition;
import com.thoughtworks.qdox.JavaProjectBuilder;
import com.thoughtworks.qdox.model.JavaClass;
import com.thoughtworks.qdox.model.JavaField;
import io.swagger.annotations.ApiModelProperty;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import springfox.documentation.schema.property.ModelSpecificationFactory;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spi.schema.ModelPropertyBuilderPlugin;
import springfox.documentation.spi.schema.contexts.ModelPropertyContext;
import springfox.documentation.spring.web.DescriptionResolver;
import springfox.documentation.swagger.common.SwaggerPluginSupport;

import java.lang.reflect.Field;
import java.util.Optional;

import static java.util.Optional.*;
import static springfox.documentation.schema.Annotations.*;

@Component
@Order(SwaggerPluginSupport.SWAGGER_PLUGIN_ORDER)
public class DocApiModelPropertyPropertyBuilder implements ModelPropertyBuilderPlugin {
    private final DescriptionResolver descriptions;
    private final ModelSpecificationFactory modelSpecifications;

    private final JavaProjectBuilder javaProjectBuilder;
    @Autowired
    public DocApiModelPropertyPropertyBuilder(
            JavaProjectBuilder javaProjectBuilder,
            DescriptionResolver descriptions,
            ModelSpecificationFactory modelSpecifications) {
        this.javaProjectBuilder = javaProjectBuilder;
        this.descriptions = descriptions;
        this.modelSpecifications = modelSpecifications;
    }

    @SuppressWarnings("deprecation")
    @Override
    public void apply(ModelPropertyContext context) {
        try {
            Optional<BeanPropertyDefinition> beanPropertyDefinition = context.getBeanPropertyDefinition();
            BeanPropertyDefinition beanPropertyDefinition1 = beanPropertyDefinition.get();
            AnnotatedField field = beanPropertyDefinition1.getField();
            Field annotated = field.getAnnotated();
            Class<?> declaringClass = annotated.getDeclaringClass();
            JavaClass classByName = javaProjectBuilder.getClassByName(((Class) declaringClass).getName());
            if(classByName !=null){
                JavaField fieldByName = classByName.getFieldByName(annotated.getName());
                if(fieldByName!=null){
                    context.getSpecificationBuilder()
                    .description(fieldByName.getComment());
                    context.getBuilder().description(fieldByName.getComment());
                }
            }
        }catch (Exception e){

        }
    }

    @Override
    public boolean supports(DocumentationType delimiter) {
        return SwaggerPluginSupport.pluginDoesApply(delimiter);
    }
}
